import axios from 'axios'
import router from '../router'
import { useUserStore } from '@/store/modules/user'
import { message, Modal } from 'ant-design-vue';
const request = axios.create({
  baseURL: process.env.BASE_URL,
  timeout: 6000
})


request.interceptors.request.use(config => {
  const userStore = useUserStore()
  const token = userStore.getToken
  if (token) {
    config.headers['Authorization'] = token
  }
  return config
})
let flag = true
request.interceptors.response.use((response) => {
  const res = response.data
  if (response.config.responseType == 'blob') {
    return res
  }
  if (res.code !== 200) {
    if (res.code === 22) {
      const userStore = useUserStore()
      Modal.confirm({
        title: '提示',
        content: 'token过期',
        okText: '重新登录',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          userStore.setToken('')
          userStore.setUserInfo('')
          setTimeout(() => {
            router.replace({ path: '/login/index' })
          }, 1000)
        },
        onCancel() {
          console.log('Cancel');
        },
      })
    } else if(res.code === 500) {
      message.error(res.msg)
    }
    return Promise.reject(new Error(res.msg || 'Error'))
  } else {
    return res;
  }
})

export default request

